package com.example.chamberlainserver.controller;

import com.example.chamberlainserver.Entry.Class;
import com.example.chamberlainserver.Service.ClassService;
import com.example.chamberlainserver.dto.ClassDTO;
import com.example.chamberlainserver.dto.PageResult;
import com.example.chamberlainserver.Vo.Response.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * 班级管理控制器
 */
@RestController
@RequestMapping("/classes")
@Validated
public class ClassController {

    @Autowired
    private ClassService classService;

    /**
     * 查询所有班级
     */
    @GetMapping("/list")
    public ResponseEntity<ApiResponse<List<Class>>> getAllClasses() {
        try {
            List<Class> classes = classService.getAllClasses();
            return ResponseEntity.ok(ApiResponse.success("查询班级列表成功", classes));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("查询班级列表失败: " + e.getMessage()));
        }
    }

    /**
     * 根据ID查询班级
     */
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Class>> getClassById(@PathVariable @NotNull Long id) {
        try {
            Class classInfo = classService.getClassById(id);
            if (classInfo != null) {
                return ResponseEntity.ok(ApiResponse.success("查询班级成功", classInfo));
            } else {
                return ResponseEntity.ok(ApiResponse.error("班级不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("查询班级失败: " + e.getMessage()));
        }
    }

    /**
     * 根据班级代码查询班级
     */
    @GetMapping("/code/{classCode}")
    public ResponseEntity<ApiResponse<Class>> getClassByCode(@PathVariable @NotEmpty String classCode) {
        try {
            Class classInfo = classService.getClassByCode(classCode);
            if (classInfo != null) {
                return ResponseEntity.ok(ApiResponse.success("查询班级成功", classInfo));
            } else {
                return ResponseEntity.ok(ApiResponse.error("班级不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("查询班级失败: " + e.getMessage()));
        }
    }

    /**
     * 分页查询班级
     */
    @GetMapping("/page")
    public ResponseEntity<ApiResponse<PageResult<Class>>> getClassesByPage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String className,
            @RequestParam(required = false) String grade,
            @RequestParam(required = false) String major,
            @RequestParam(required = false) String department,
            @RequestParam(required = false) Integer status) {
        try {
            PageResult<Class> result = classService.getClassesByPage(page, size, className, grade, major, department, status);
            return ResponseEntity.ok(ApiResponse.success("分页查询班级成功", result));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("分页查询班级失败: " + e.getMessage()));
        }
    }

    /**
     * 创建班级
     */
    @PostMapping
    public ResponseEntity<ApiResponse<Class>> createClass(@RequestBody @Valid ClassDTO classDTO) {
        try {
            // 验证班级代码唯一性
            if (!classService.isClassCodeUnique(classDTO.getClassCode(), null)) {
                return ResponseEntity.ok(ApiResponse.error("班级代码已存在"));
            }
            
            // 验证班级名称唯一性
            if (!classService.isClassNameUnique(classDTO.getClassName(), null)) {
                return ResponseEntity.ok(ApiResponse.error("班级名称已存在"));
            }
            
            Class classInfo = classService.createClass(classDTO);
            return ResponseEntity.ok(ApiResponse.success("创建班级成功", classInfo));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("创建班级失败: " + e.getMessage()));
        }
    }

    /**
     * 更新班级信息
     */
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Class>> updateClass(@PathVariable @NotNull Long id, 
                                   @RequestBody @Valid ClassDTO classDTO) {
        try {
            // 验证班级是否存在
            Class existingClass = classService.getClassById(id);
            if (existingClass == null) {
                return ResponseEntity.ok(ApiResponse.error("班级不存在"));
            }
            
            // 验证班级代码唯一性
            if (!classService.isClassCodeUnique(classDTO.getClassCode(), id)) {
                return ResponseEntity.ok(ApiResponse.error("班级代码已存在"));
            }
            
            // 验证班级名称唯一性
            if (!classService.isClassNameUnique(classDTO.getClassName(), id)) {
                return ResponseEntity.ok(ApiResponse.error("班级名称已存在"));
            }
            
            Class classInfo = classService.updateClass(id, classDTO);
            return ResponseEntity.ok(ApiResponse.success("更新班级成功", classInfo));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("更新班级失败: " + e.getMessage()));
        }
    }

    /**
     * 删除班级
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<String>> deleteClass(@PathVariable @NotNull Long id) {
        try {
            boolean success = classService.deleteClass(id);
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("删除成功", "删除成功"));
            } else {
                return ResponseEntity.ok(ApiResponse.error("删除失败，班级不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("删除班级失败: " + e.getMessage()));
        }
    }

    /**
     * 批量删除班级
     */
    @DeleteMapping("/batch")
    public ResponseEntity<ApiResponse<String>> deleteClasses(@RequestBody @NotEmpty List<Long> ids) {
        try {
            int deletedCount = classService.deleteClasses(ids);
            return ResponseEntity.ok(ApiResponse.success("批量删除成功", "成功删除 " + deletedCount + " 个班级"));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("批量删除班级失败: " + e.getMessage()));
        }
    }

    /**
     * 根据辅导员ID获取班级列表
     */
    @GetMapping("/counselor/{counselorId}")
    public ResponseEntity<ApiResponse<List<Class>>> getClassesByCounselorId(@PathVariable @NotNull Long counselorId) {
        try {
            List<Class> classes = classService.getClassesByCounselorId(counselorId);
            return ResponseEntity.ok(ApiResponse.success("获取班级列表成功", classes));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取班级列表失败: " + e.getMessage()));
        }
    }

    /**
     * 获取未分配辅导员的班级列表
     */
    @GetMapping("/unassigned")
    public ResponseEntity<ApiResponse<List<Class>>> getUnassignedClasses() {
        try {
            List<Class> classes = classService.getUnassignedClasses();
            return ResponseEntity.ok(ApiResponse.success("获取未分配班级列表成功", classes));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取未分配班级列表失败: " + e.getMessage()));
        }
    }

    /**
     * 根据年级获取班级列表
     */
    @GetMapping("/grade/{grade}")
    public ResponseEntity<ApiResponse<List<Class>>> getClassesByGrade(@PathVariable @NotNull String grade) {
        try {
            List<Class> classes = classService.getClassesByGrade(grade);
            return ResponseEntity.ok(ApiResponse.success("获取班级列表成功", classes));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取班级列表失败: " + e.getMessage()));
        }
    }

    /**
     * 根据专业查询班级
     */
    @GetMapping("/major/{major}")
    public ResponseEntity<ApiResponse<List<Class>>> getClassesByMajor(@PathVariable @NotEmpty String major) {
        try {
            List<Class> classes = classService.getClassesByMajor(major);
            return ResponseEntity.ok(ApiResponse.success("获取班级列表成功", classes));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取班级列表失败: " + e.getMessage()));
        }
    }

    /**
     * 根据年级和专业查询班级
     */
    @GetMapping("/grade/{grade}/major/{major}")
    public ResponseEntity<ApiResponse<List<Class>>> getClassesByGradeAndMajor(@PathVariable @NotEmpty String grade, 
                                                       @PathVariable @NotEmpty String major) {
        try {
            List<Class> classes = classService.getClassesByGradeAndMajor(grade, major);
            return ResponseEntity.ok(ApiResponse.success("获取班级列表成功", classes));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取班级列表失败: " + e.getMessage()));
        }
    }

    /**
     * 更新班级状态
     */
    @PatchMapping("/{id}/status")
    public ResponseEntity<ApiResponse<String>> updateClassStatus(@PathVariable @NotNull Long id, 
                                          @RequestBody Map<String, Integer> statusMap) {
        try {
            Integer status = statusMap.get("status");
            if (status == null) {
                return ResponseEntity.ok(ApiResponse.error("状态参数不能为空"));
            }
            
            boolean success = classService.updateClassStatus(id, status);
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("状态更新成功", "状态更新成功"));
            } else {
                return ResponseEntity.ok(ApiResponse.error("状态更新失败，班级不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("更新班级状态失败: " + e.getMessage()));
        }
    }

    /**
     * 获取所有年级列表
     */
    @GetMapping("/grades")
    public ResponseEntity<ApiResponse<List<String>>> getAllGrades() {
        try {
            List<String> grades = classService.getAllGrades();
            return ResponseEntity.ok(ApiResponse.success("获取年级列表成功", grades));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("查询年级列表失败: " + e.getMessage()));
        }
    }

    /**
     * 获取所有专业列表
     */
    @GetMapping("/majors")
    public ResponseEntity<ApiResponse<List<String>>> getAllMajors() {
        try {
            List<String> majors = classService.getAllMajors();
            return ResponseEntity.ok(ApiResponse.success("获取专业列表成功", majors));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("查询专业列表失败: " + e.getMessage()));
        }
    }

    /**
     * 获取所有院系列表
     */
    @GetMapping("/departments")
    public ResponseEntity<ApiResponse<List<String>>> getAllDepartments() {
        try {
            List<String> departments = classService.getAllDepartments();
            return ResponseEntity.ok(ApiResponse.success("获取院系列表成功", departments));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("查询院系列表失败: " + e.getMessage()));
        }
    }
}